package com.zc.RecordDemo;/**
 * Created by admin on 2016/8/1.
 */

import android.content.Context;
import android.media.MediaPlayer;
import android.util.Log;

import java.io.IOException;

import static android.content.ContentValues.TAG;

/**
 * 项目名称：
 * 类名称：
 * 类描述：
 * 创建人：
 * 创建时间：
 * 修改人：
 * 修改时间：
 * 修改备注：
 *
 * @version V1.0
 */
public class MediaPlayerManager {
    private MediaPlayer mPlayer = null;

    private Context mContext;
    String mDataSource;

    MediaPlayerManager(Context context) {
        mContext = context;
        mPlayer = new MediaPlayer();
    }

    public MediaPlayer getMediaPlayer() {
        return mPlayer;
    }


    public void setDataSource(String path) {
        mDataSource = path;
    }

    public void start() {
        try {
            mPlayer.setDataSource(mDataSource);
            mPlayer.prepare();
            mPlayer.start();
            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    //mp.stop();
                    //mPlayer.release();
                    //mPlayer = null;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void startPlaying(String path) {
        //mPlayer = MediaPlayer.create(mContext, Uri.parse(path));//实例化 MediaPlayer 并添加音频
        Log.e(TAG, "startPlayingstartPlaying");
        if (mPlayer != null) {
            return;
        }
        try {
            mPlayer.setDataSource(path);
            mPlayer.prepare();
            mPlayer.start();
            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mPlayer.release();
                    mPlayer = null;
                }
            });
        } catch (IOException e) {
            Log.e(TAG, e.toString() + "\nprepare() failed");
        }
    }


    public void stopPlaying() {
        Log.e(TAG, "stopPlaying");
        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }

    public void release() {
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.release();
            mPlayer = null;
        }
    }
}
